import Vue from 'vue'
import Router from 'vue-router'
import Home from '~/views/home'
import Login from '~/views/Login'
import Page4 from '~/components/nav4/Page4'
import Page2 from '~/components/nav2/Page2'
import NotFound from '~/views/404'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      children: [
        { path: '/page4', component: Page4, name: '页面4' },
        { path: '/page2', component: Page2, name: '页面2' }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      beforeEnter: (to, from, next) => {
        // 局部钩子
        next()
      }
    },
    {
      path: '*',
      redirect: { path: '/404' }
    },
    {
      path: '/404',
      component: NotFound,
      name: '',
      hidden: true
    }
  ]
})

router.beforeEach((to, from, next) => {
  // 全局钩子
  if (to.path === '/login') {
    sessionStorage.removeItem('user')
  }
  let user = sessionStorage.getItem('username')
  if (!user && to.path !== '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})

export default router
